package ccb.ygqd.inspur.common;

import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;

import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.SiecomDevice;
import com.siecomzg.transport.usb.USBClient;
import com.siecomzg.transport.usb.receiver.OpenDevicesReceiver;
import com.siecomzg.transport.usb.receiver.UsbDetachedReceiver;

import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * hengfeng项目专用接口
 * 超时时间 单位 秒 s
 */
public class CommonHF implements UsbDetachedReceiver.UsbDetachedListener, OpenDevicesReceiver.OpenDevicesListener{

    private UsbDevice mUsbDevice;
    public UsbDetachedReceiver mUsbDetachedReceiver;
    public OpenDevicesReceiver mOpenDevicesReceiver;
    private static final String USB_ACTION = "com.siecom.zhq.client";
    public UsbManager mUsbManager ;
    public USBClient mUSBClient ;

    public static final String TAG = CommonHF.class.getSimpleName();
    public static final String PIN = "PIN";
    public static final String ICC = "IC1";
    public static final String PIC = "ICC";
    public static final String CDB = "CDB";
    public static final String FIG = "FIG";
    public static final String YGB = "YGB";
    public static final String RDC = "RDC";
    public static final String IDC = "IDC";
    public static final String CFG = "CFG";


    public Context mContext;
    public CommonHF(Context context){
        mContext = context;
//        if (mContext.getSharedPreferences("CommMethod",Context.MODE_PRIVATE).getString("method","").equals(ConstHF.CONN_TYPE_USB)){
//        }
        initUsb();
        SiecomDevice.setContext(mContext);
    }

    public void initUsb(){
        LogUtil.e(TAG,"initUsb ======= ");
        mUSBClient = USBClient.getInstance(mContext);
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        mUsbDetachedReceiver = new UsbDetachedReceiver(this);
        IntentFilter intentFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbDetachedReceiver, intentFilter);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(USB_ACTION), 0);
        IntentFilter intentFilter1 = new IntentFilter(USB_ACTION);
        mOpenDevicesReceiver = new OpenDevicesReceiver(this);
        mContext.registerReceiver(mOpenDevicesReceiver, intentFilter1);

        if (mUsbManager.getDeviceList().size() > 0){
            mUSBClient.openDevices();
        }

    }

    @Override
    public void openAccessoryModel(UsbDevice usbDevice) {
        LogUtil.e(TAG,"openAccessoryModel  成功了---- " + usbDevice.getProductId());
        mUsbDevice = usbDevice;
        mUSBClient.initAccessory(usbDevice);
        ConstDefine.CONNECT_TYPE = ConstDefine.CONNECT_TYPE_USB; //USB连接
    }

    @Override
    public void openDevicesError() {
        LogUtil.e(TAG,"openDevicesError  ---- " );
    }

    @Override
    public void usbDetached() {
        LogUtil.e(TAG,"usbDetached 断开了连接 ------ " );
        mUSBClient.disConnect();
    }

    @Override
    public void usbAttached() {
        LogUtil.e(TAG,"usbAttached usb 连接 ------ " );
        mUSBClient.openDevices();
        ConstDefine.CONNECT_TYPE = ConstDefine.CONNECT_TYPE_USB; //USB连接
    }

    /**
     * 获取各个设备模块的状态
     * @param strDevType  密码键盘：PIN
     * 非接触式IC卡：ICC
     * 接触式IC卡：IC1（原为CDB）。
     * 发卡箱：CDB
     * 指纹仪：FIG
     * 电子签名：YGB
     * 磁条刷卡器：RDC
     * 二代证：IDC
     * 居民指纹仪：CFG
     * @param strTimeout 超时
     * @return
     */
    public String[] getDevStatus(final String strDevType, String strTimeout){
        LogUtil.e(TAG,"getDevStatus ----- conn == " + SiecomDevice.isConnected);
        final String ret[] = new String[]{"","",""};
        int timeOut = Integer.parseInt(strTimeout);
        if (!SiecomDevice.isConnected){
            switch (strDevType){
                case PIN:
                    ret[0] = ConstHF.STATE_PIN_OFFLINE;
                    break;

                case ICC:
                    ret[0] = ConstHF.STATE_ICC_OFFLINE;
                    break;
                case PIC:
                    ret[0] = ConstHF.STATE_PIC_OFFLINE;
                    break;

                case CDB:
                    ret[0] = ConstHF.STATE_CARD_BOX_OFFLINE;
                    break;

                case FIG:
                    ret[0] = ConstHF.STATE_FIG_OFFLINE;
                    break;

                case YGB:
                    ret[0] = ConstHF.STATE_SIGN_OFFLINE;
                    break;
                case RDC:
                    ret[0] = ConstHF.STATE_MSR_OFFLINE;
                    break;
                case IDC:
                    ret[0] = ConstHF.STATE_ID_OFFLINE;
                    break;
                case CFG:
                    ret[0] = ConstHF.STATE_CFG_OFFLINE;
                    break;

                default:
                    ret[0] = ConstHF.ERR_PARAM;  //传入的参数错误
                    break;
            }

            return ret;
        }

        final CountDownLatch latch = new CountDownLatch(1);

        SiecomDevice.checkDeviceModuleState("",new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                ret[0] = ConstHF.ERR_HARDWARE;
                ret[1] = "设备故障，请尝试重启";
                latch.countDown();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                switch (strDevType){
                    case PIN:
                        ret[0] = ConstHF.STATE_PIN_NORMAL;
                        break;

                    case ICC:
                        ret[0] = ConstHF.STATE_ICC_NORMAL;
                        break;
                    case PIC:
                        ret[0] = ConstHF.STATE_PIC_NORMAL;
                        break;

                    case CDB:
                        ret[0] = ConstHF.STATE_CARD_BOX_NORMAL;
                        break;

                    case FIG:
                        ret[0] = ConstHF.STATE_FIG_NORMAL;
                        break;

                    case YGB:
                        ret[0] = ConstHF.STATE_SIGN_NORMAL;
                        break;
                    case RDC:
                        ret[0] = ConstHF.STATE_MSR_NORMAL;
                        break;
                    case IDC:
                        ret[0] = ConstHF.STATE_ID_NORMAL;
                        break;
                    case CFG:
                        ret[0] = ConstHF.STATE_CFG_NORMAL;
                        break;

                    default:
                        ret[0] = ConstHF.ERR_PARAM;  //传入的参数错误
                        break;
                }
                latch.countDown();
            }

            @Override
            public void onCompleted(Bundle bundle) {
                latch.countDown();
            }
        },timeOut*1000,false);
        try {
            latch.await(timeOut+1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        return ret;
    }

    /**
     * 强制复位指定的设备，不管设备忙不忙
     * @param strDevType 如PIN代表密码键盘
     * @return
     */
    public String[] resetDev(String strDevType){
        LogUtil.e(TAG,"resetDev ----- conn == " + SiecomDevice.isConnected + " ---- " + strDevType);
        final String ret[] = new String[]{"","",""};
        if (!SiecomDevice.isConnected){
            ret[0] = ConstHF.ERR_NOT_CONN;
            ret[1] = ConstHF.ERR_DEV_ONT_CONN;
            return ret;
        }
        int timeOut = 5;


        final CountDownLatch latch = new CountDownLatch(1);

        SiecomDevice.resetModule(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                ret[0] = ConstHF.ERR_HARDWARE;
                ret[1] = "设备故障，请尝试重启";
                latch.countDown();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                ret[0] = ConstHF.ERR_SUCCESS;
                latch.countDown();
            }

            @Override
            public void onCompleted(Bundle bundle) {
                latch.countDown();
            }
        },timeOut*1000,false);
        try {
            latch.await(timeOut+1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return ret;

    }

    /**
     * aryRet[0]状态指示码。DRV0000000为正确，aryRet[1]为设备信息的JSON串，格式为：
     * {“SN”：“移动外设序列号”，“BluetoothMac”：“蓝牙mac地址”，“Module”：“移动外设设备型号”，“OS”：“移动外设操作系统”，“OSVersion”:“操作系统版本号”, “appVersion”:“应用版本号”,“buildDate”：“应用build日期（格式YYYYMMDD，如20190101）”，“ProductionDate”:“出厂日期（YYYYMMDD）”，“fingerprintType”：“指纹仪类型（FIG：普通指纹仪；CFG：居民指纹仪；ALL：两者均支持。返回值示例：CFG）”}
     * @return
     */
    public String[] getDeviceInfo(){
        LogUtil.e(TAG,"getDeviceInfo ----- conn == " + SiecomDevice.isConnected);
        final String[] ret = new String[]{"",""};
        if (!SiecomDevice.isConnected){
            ret[0] = ConstHF.ERR_NOT_CONN;
            ret[1] = ConstHF.ERR_DEV_ONT_CONN;
            return ret;
        }
        final CountDownLatch latch = new CountDownLatch(1);

        SiecomDevice.getDeviceHWVersion(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                ret[0] = ConstHF.ERR_HARDWARE;
                ret[1] = "设备故障，请尝试重启";
                latch.countDown();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                ret[0] = ConstHF.ERR_SUCCESS;
                ret[1] = bundle.getString("data2");
                latch.countDown();
            }

            @Override
            public void onCompleted(Bundle bundle) {
                latch.countDown();
            }
        },10*1000,false);
        try {
            latch.await(11, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        LogUtil.e(TAG, Arrays.toString(ret));
        return ret;
    }
    /**
     * 通讯方式的设置后需长期有效
     * @param strMethod
     * usb:使用USB进行通讯。
     * bluetooth：使用蓝牙进行通讯。
     * wirelessusb：使用2.4G无线USB进行通讯。
     * @return
     */
    public String[] setCommuMethod(String strMethod){
        LogUtil.e(TAG,"setCommuMethod == " + strMethod);
        final String[] ret = new String[]{"",""};
        if(strMethod.equals("wirelessusb")){
            ret[0] = ConstHF.ERR_PARAM;
            ret[1] = "not support wirelessusb ";
            LogUtil.e(TAG,"参数错误 " );

            return ret;
        }
        if (!strMethod.equals("usb") && !strMethod.equals("bluetooth")){
            ret[0] = ConstHF.ERR_PARAM;
            ret[1] = "param error";
            LogUtil.e(TAG,"参数错误 " );

            return ret;
        }
        if (null != mContext){
            SharedPreferences p = mContext.getSharedPreferences("CommMethod",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = p.edit();
            editor.putString("method",strMethod);
            editor.apply();
            ret[0] = ConstHF.ERR_SUCCESS;
        }
        return ret;
    }


    public String[] setBlueToothMac(String strMac){
        LogUtil.e(TAG,"setBlueToothMac ----- " + strMac);
//        strMac = "DE:9F:46:03:21:95"; //先写死
        if (null != mContext){
            SharedPreferences p = mContext.getSharedPreferences("CommMethod",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = p.edit();
            editor.putString("mac",strMac);
            editor.apply();
        }
        BluetoothDevice btDevice = null;
        final CountDownLatch latch = new CountDownLatch(1);
        final String[] ret = new String[]{"",""};

            Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
            for (BluetoothDevice device :devices){
                LogUtil.e(TAG,"device.Name == " + device.getName() + "-- mac == " + device.getAddress());
                if (device.getName().startsWith("A") && device.getAddress().equals(strMac)){
                    btDevice = device;
                    break;
                }
            }
            if (btDevice != null){
                LogUtil.e(TAG,"btDevice.getName == " + btDevice.getName());
                SiecomDevice.startConnect(btDevice, new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        ret[0] = ConstHF.ERR_BLUE_CONNECT;
                        latch.countDown();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        ret[0] = ConstHF.ERR_SUCCESS;
                        ret[1] = "蓝牙连接成功";
                        latch.countDown();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {
                        latch.countDown();
                    }
                },false);

            }else {
                ret[0] = ConstHF.ERR_BLUE_CONNECT;
                ret[1] = "连接失败，请重试";
            }


        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }




}
